package com.mdd.admin.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.service.order.IOrderClueService;
import com.mdd.admin.validate.order.*;
import com.mdd.admin.vo.order.OrderClueAllocationRecordVo;
import com.mdd.admin.vo.order.OrderClueDetailVo;
import com.mdd.admin.vo.order.OrderClueVo;
import com.mdd.common.base.page.PageValidate;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.order.OrderClue;
import com.mdd.common.entity.order.OrderClueAllocationRecord;
import com.mdd.common.entity.order.OrderClueList;
import com.mdd.common.enums.clue.ClueAllocationRecordStatusEnum;
import com.mdd.common.enums.clue.ClueAllocationRecordTypeEnum;
import com.mdd.common.mapper.order.OrderClueAllocationRecordMapper;
import com.mdd.common.mapper.order.OrderClueMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.common.validate.IdValidate;
import com.mdd.system.RtAdminThreadLocal;
import com.mdd.system.entity.SystemAuthAdmin;
import com.mdd.system.entity.SystemAuthDept;
import com.mdd.system.mapper.SystemAuthDeptMapper;
import com.mdd.system.vo.SystemAuthAdminInformVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.util.*;

/**
 * 订单实现类
 * @author LikeAdmin
 */
@Service
public class OrderClueServiceImpl implements IOrderClueService {

    @Resource
    OrderClueMapper orderClueMapper;
    @Resource
    OrderClueAllocationRecordMapper  orderClueAllocationRecordMapper;
    @Resource
    SystemAuthDeptMapper systemAuthDeptMapper;
    /**
     * 订单列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<OrderClueListedVo>
     */
    @Override
    public PageResult<OrderClueVo> list(PageValidate pageValidate, OrderClueSearchValidate searchValidate, SystemAuthAdminInformVo systemAuthAdmin) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        Map params = new HashMap();
        if(Objects.nonNull(searchValidate.getChannel())){
            params.put("channel",searchValidate.getChannel());
        }
        if(Objects.nonNull(searchValidate.getQualificationCertificate())){
            params.put("qualificationCertificate",searchValidate.getQualificationCertificate());
        }
        if(Objects.nonNull(searchValidate.getCarFrom())){
            params.put("carFrom",searchValidate.getCarFrom());
        }
        if(StringUtils.isNotEmpty(searchValidate.getWillingCity())){
            params.put("willingCity",searchValidate.getWillingCity());
        }
        if(StringUtils.isNotEmpty(searchValidate.getDeptName())){
            params.put("deptName",searchValidate.getDeptName());
        }
        SystemAuthDept systemAuthDept = systemAuthDeptMapper.selectById(systemAuthAdmin.getDeptIds());
        //非平台部门 加入部门编码模糊查询
        if(!systemAuthDept.getType().equals(0)) {
            params.put("deptCode", systemAuthAdmin.getDeptCode());
        }
        IPage<OrderClueList> iPage = orderClueMapper.selectCluePage(new Page<>(page, limit), params);
        List<OrderClueVo> orderClueVoList = new ArrayList<>();
        for(OrderClueList orderClue : iPage.getRecords()){
            OrderClueVo orderClueVo = new OrderClueVo();
            BeanUtils.copyProperties(orderClue,orderClueVo);
            //"状态 0待分配 1已分配  2跟进中 3已上岗 4已流失   9已作废"
            if(orderClue.getDeptId().equals(systemAuthAdmin.getDeptIds())){

                orderClueVo.setAllowOperator(true);
                //0待分配 1已分配 根据线索所在层级判断 ，其它状态直接获取
                if(orderClue.getStatus().equals(0)|| orderClue.getStatus().equals(1)) {
                    orderClueVo.setStatus(0);
                }
                List<Map> allowUpdateStatus = new ArrayList<>();
                if(systemAuthDept.getType().equals(0)){
                    allowUpdateStatus.add(ClueAllocationRecordStatusEnum.ON_DUTY_STATUS.enumToMap());
                    allowUpdateStatus.add(ClueAllocationRecordStatusEnum.VOIDED_STATUS.enumToMap());
                }else if(systemAuthDept.getType().equals(1)|| systemAuthDept.getType().equals(2)){
                    //已上岗状态不能再进行其它操作
                    if(!orderClue.getStatus().equals(3)) {
                        allowUpdateStatus.add(ClueAllocationRecordStatusEnum.FOLLOW_UP_STATUS.enumToMap());
                        allowUpdateStatus.add(ClueAllocationRecordStatusEnum.LOST_STATUS.enumToMap());
                    }
                }

                orderClueVo.setAllowUpdateStatus(allowUpdateStatus);

            }else {
                orderClueVo.setAllowOperator(false);
                //0待分配 1已分配 根据线索所在层级判断 ，其它状态直接获取
                if(orderClue.getStatus().equals(0)|| orderClue.getStatus().equals(1)) {
                    orderClueVo.setStatus(1);
                }
            }
            orderClueVoList.add(orderClueVo);

        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), orderClueVoList);
    }


    /**
     * 订单新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Transactional
    @Override
    public OrderClueVo add(OrderClueCreateValidate createValidate) {

        //新增订单基础信息
        OrderClue model = new OrderClue();
        BeanUtils.copyProperties(createValidate,model);
        //0待认领
        model.setStatus(0);
        //设置默认部门
        model.setDeptId(1L);
        model.setDeptCode("1");
        orderClueMapper.insert(model);
        OrderClueVo orderClueVo = new OrderClueVo();
        BeanUtils.copyProperties(model,orderClueVo);
        return  orderClueVo;
    }

    @Transactional
    @Override
    public void batchInsert(List<OrderClue> orderClueList) {
        orderClueMapper.batchInsertOrderClue(orderClueList);
    }
        @Override
    public OrderClueDetailVo detail(IdValidate idValidate) {
        OrderClue model = orderClueMapper.selectById(idValidate.getId());
        Assert.notNull(model, "线索数据不存在!");
        OrderClueDetailVo orderClueDetailVo = new OrderClueDetailVo();
        BeanUtils.copyProperties(model,orderClueDetailVo);
        SystemAuthDept systemAuthDept = systemAuthDeptMapper.selectById(model.getDeptId());
        orderClueDetailVo.setDeptName(systemAuthDept.getName());
        List<OrderClueAllocationRecord> orderClueAllocationRecords = orderClueAllocationRecordMapper.
                selectList(new LambdaQueryWrapper<OrderClueAllocationRecord>()
                        .eq(OrderClueAllocationRecord::getClueId,idValidate.getId()).orderByAsc(OrderClueAllocationRecord::getId));
        List<OrderClueAllocationRecordVo> orderClueAllocationRecordVos = new ArrayList<>();
        orderClueAllocationRecords.forEach(orderClueAllocationRecord -> {
            OrderClueAllocationRecordVo orderClueAllocationRecordVo = new OrderClueAllocationRecordVo();
            BeanUtils.copyProperties(orderClueAllocationRecord,orderClueAllocationRecordVo);
            orderClueAllocationRecordVos.add(orderClueAllocationRecordVo);
        });
        orderClueDetailVo.setOrderClueAllocationRecords(orderClueAllocationRecordVos);
        return orderClueDetailVo;
    }



    @Transactional
    @Override
    public void allocation(OrderClueClaimValidate orderClueClaimValidate,SystemAuthAdminInformVo systemAuthAdmin) {
        SystemAuthDept systemAuthDept= systemAuthDeptMapper.selectById(orderClueClaimValidate.getDeptId());
        String[] clueIds = orderClueClaimValidate.getOrderClueIds().split(",");
        for(String clueId :clueIds){
            OrderClue orderClue =orderClueMapper.selectById(clueId);
            orderClue.setDeptId(orderClueClaimValidate.getDeptId());
            orderClue.setDeptCode(systemAuthDept.getDeptCode());
            //已流失分配时将状态更改为 已分配
            if(orderClue.getStatus().equals(ClueAllocationRecordStatusEnum.LOST_STATUS.getCode())){
                orderClue.setStatus(ClueAllocationRecordStatusEnum.ALLOCATION_STATUS.getCode());
            }
            orderClueMapper.updateById(orderClue);
        }
        Long sourceOrgId =  Long.valueOf(RtAdminThreadLocal.get("deptIds").toString());
        String sourceOrgCode =  RtAdminThreadLocal.get("deptCode").toString();
        Map params =new HashMap();
        params.put("orderClueIds",clueIds);
        params.put("sourceDeptId",sourceOrgId);
        params.put("sourceDeptCode",sourceOrgCode);
        params.put("targetDeptId", orderClueClaimValidate.getDeptId());
        params.put("targetDeptCode",systemAuthDept.getDeptCode());
        params.put("type", ClueAllocationRecordTypeEnum.ALLOCATION.getCode());
        StringBuilder content = new StringBuilder()
                .append(systemAuthAdmin.getNickname()).append(" 源部门：").append(systemAuthDept.getName()).append(";");
        content.append(" 操作：").append(ClueAllocationRecordTypeEnum.ALLOCATION.getMsg());
        content.append(" 目标部门：").append(systemAuthDept.getName());
        params.put("content",content.toString());
        orderClueAllocationRecordMapper.batchAddOrderClueAllocationRecord(params);

    }


    /**
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Transactional
    @Override
    public void edit(OrderClueUpdateValidate updateValidate) {
        OrderClue model = orderClueMapper.selectById(updateValidate.getId());
        Assert.notNull(model, "线索数据不存在!");
        model.setChannel(updateValidate.getChannel());
        model.setAvailableDate(updateValidate.getAvailableDate());
        model.setDriverName(updateValidate.getDriverName());
        model.setPhoneNumber(updateValidate.getPhoneNumber());
        model.setWillingCity(updateValidate.getWillingCity());
        model.setQualificationCertificate(updateValidate.getQualificationCertificate());
        orderClueMapper.updateById(model);
    }

    @Transactional
    @Override
    public void updateStatus(OrderClueUpdateStatusValidate updateValidate,SystemAuthAdminInformVo systemAuthAdmin) {
        //todo 加入校验
        SystemAuthDept systemAuthDept = systemAuthDeptMapper.selectById(systemAuthAdmin.getDeptIds());
        //状态 0待分配 1已分配  2跟进中 3已上岗 4已流失 5公海 9已作废
        OrderClueAllocationRecord orderClueAllocationRecord = new OrderClueAllocationRecord();
        orderClueAllocationRecord.setClueId(updateValidate.getId());
        orderClueAllocationRecord.setSourceDeptId(systemAuthAdmin.getDeptIds());
        orderClueAllocationRecord.setSourceDeptCode(systemAuthAdmin.getDeptCode());
        orderClueAllocationRecord.setType(ClueAllocationRecordTypeEnum.CHANGE_STATUS.getCode());
        orderClueAllocationRecord.setRemark(updateValidate.getRemark());
        StringBuilder content = new StringBuilder()
                .append(systemAuthAdmin.getNickname()).append(" 源部门：").append(systemAuthDept.getName()).append(",");
        content.append(" 操作：").append(ClueAllocationRecordTypeEnum.CHANGE_STATUS.getMsg())
                .append(ClueAllocationRecordStatusEnum.getStatusByCode(updateValidate.getStatus()).getMsg());

        OrderClue model = orderClueMapper.selectById(updateValidate.getId());
        Assert.notNull(model, "线索数据不存在!");
        model.setStatus(updateValidate.getStatus());
        if(updateValidate.getStatus().equals(ClueAllocationRecordStatusEnum.LOST_STATUS.getCode())){
            // 已流失 数据回流至如通平台
            model.setDeptId(1L);
            model.setDeptCode("1");
            content.append(" 目标部门：如通;");
        }
        orderClueAllocationRecord.setContent(content.toString());
        orderClueAllocationRecordMapper.insert(orderClueAllocationRecord);
        //新增记录
        orderClueMapper.updateById(model);
    }


    /**
     * 订单删除c'la
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Transactional
    @Override
    public void del(Long id) {
        OrderClue model = orderClueMapper.selectById(id);

        Assert.notNull(model, "线索数据不存在!");

        orderClueMapper.deleteById(id);
    }

}
